import { message, Upload } from 'antd/es';
import { PlusOutlined} from '@ant-design/icons';
import React, { useEffect, useState } from "react";
import { request } from "@@/plugin-request/request";
import type { UploadFile } from "antd/es/upload/interface";
// @ts-ignore
import lrz from 'lrz';
import 'antd/es/upload/style';
import { RcFile } from "antd/lib/upload";


const AliyunOSSUpload: React.FC<{ value?: string[] | string, onChange?: any, multiple?: boolean, fileType?: "img" | "video" | undefined }>
  = ({
       value,
       onChange,
       multiple,
       fileType
     }) => {

  const [state, setState] = useState({
    OSSData: {
      host: '',
      expire: 0,
      dir: '',
      accessId: '',
      policy: '',
      signature: ''
    },
    fileList:
      value && ((typeof value === "string" ? [{
        uid: 0,
        name: value,
        status: 'done',
        url: value
      }] : value.map((it, i) => {
        return {
          uid: i.toString(),
          name: it,
          status: 'done',
          url: it
        }
      })) as UploadFile[]) || []
  })

  const getOSSData = async () => {
    return request(`${process.env.hostname}/api/oss/policy`)
  };

  const init = async () => {
    try {
      const OSSData = await getOSSData();
      setState({ ...state, OSSData });
    } catch (error) {
      message.error(error);
    }
  };

  useEffect(() => {
    init()
  }, [])

  const getExtraData = (file: any) => {
    const { OSSData } = state;

    return {
      key: file.ossKey,
      OSSAccessKeyId: OSSData.accessId,
      policy: OSSData.policy,
      Signature: OSSData.signature,
    };
  };

  const beforeUpload = async (file: RcFile) => {
    const { OSSData } = state;
    const expire = OSSData.expire * 1000;
    if (expire < Date.now()) {
      await init();
    }
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const rand = Math.floor(Math.random() * 1000)
    const filename = `${Date.now()}-${rand}${suffix}`;

    if (fileType === "img") {
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        message.error('仅支持图片类型')
        return new Promise((resolve, reject)=>{reject(new Error('仅支持图片类型'))})
      }

      return lrz(file, { quality: 0.9, width: 800 }).then((res: any) => {
        return new Promise((resolve, reject) => {
          if (res instanceof Object) {
            // console.log(res)
            Object.assign(res.file, {
              url: `${OSSData.host}/${OSSData.dir}${filename}`,
              ossKey: OSSData.dir + filename,
              uid: filename
            });
            resolve(res.file);
          } else {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject('压缩失败')
          }
        })
      })


    }
    if (fileType === "video") {
      if (!file.type.startsWith("video/")) {
        message.error('仅支持视频类型')
        return new Promise((resolve, reject)=>{reject(new Error('仅支持视频类型'))})
      }
    }

    // if (file.type === "image/png" || file.type === "image/jpeg") {
    //   return lrz(file, { quality: 0.9, width: 800 }).then((res: any) => {
    //     return new Promise((resolve, reject) => {
    //       if (res instanceof Object) {
    //         // console.log(res)
    //         Object.assign(res.file, {
    //           url: `${OSSData.host}/${OSSData.dir}${filename}`,
    //           ossKey: OSSData.dir + filename,
    //           uid: filename
    //         });
    //         resolve(res.file);
    //       } else {
    //         // eslint-disable-next-line prefer-promise-reject-errors
    //         reject('压缩失败')
    //       }
    //     })
    //   })
    // }

    return Object.assign(file, {
      url: `${OSSData.host}/${OSSData.dir}${filename}`,
      ossKey: OSSData.dir + filename,
      uid: filename
    });

  };

  const handleChange = (info: { fileList: any, file: any }) => {
    const fileList = [...info.fileList]

    // console.log(fileList)

    setState(p => {
      return { ...p, fileList }
    })
    // setState({ ...state, fileList })
    let urls
    if (multiple) {
      urls = fileList.map(it => it.url)
    } else {
      urls = fileList[0] && fileList[0].url || null
    }

    // console.log(urls)

    if (onChange) {
      onChange(urls);
    }
  };

  return (
    <Upload
      name='file'
      fileList={state.fileList}
      action={state.OSSData.host}
      onChange={handleChange}
      data={getExtraData}
      beforeUpload={beforeUpload}
      listType={"picture-card"}
      maxCount={multiple ? 50 : 1}
      multiple={multiple}
    >
      {state.fileList.length >= 50 ? null : <PlusOutlined />}
    </Upload>
  );
}

export { AliyunOSSUpload }
